<!--
 * @Author: jswang
 * @Date: 2021-08-01 14:26:56
 * @LastEditTime: 2021-08-02 15:19:17
-->
<template>
  <el-dialog
    :title="showTitle"
    :visible="showDialog"
    width="width"
    @close="btnCancel"
  >
    <!-- 表单 -->
    <el-form
      label-width="120px"
      :model="addDeptsFormData"
      :rules="addDeptsRules"
      ref="addDeptsFormRef"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          style="width:80%"
          placeholder="1-50个字符"
          v-model="addDeptsFormData.name"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          style="width:80%"
          placeholder="1-50个字符"
          v-model="addDeptsFormData.code"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" style="width:80%" prop="manager">
        <el-select
          placeholder=""
          v-model="addDeptsFormData.manager"
          @focus="getEmployeeSimple"
        >
          <el-option
            v-for="item in peoples"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          style="width:80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="4"
          v-model="addDeptsFormData.introduce"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 确定和取消 -->
    <el-row type="flex" justify="center" slot="footer">
      <el-col :span="6">
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button size="small" type="primary" @click="btnOk">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import {
  getDepartments,
  addDepartments,
  getDepartmentDetail,
  updateDepartments
} from "@/api/departments";
import { getEmployeeSimple } from "@/api/employees";
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    //检查部门名称是否重复
    const checkNameRepeat = async (rule, value, callback) => {
      //value 是部门名称 要去和同级部门下的部门比较,有没有相同的,有相同的不能过, 不相同就可以过
      const { depts } = await getDepartments();
      let isRepeat = false;
      if (this.addDeptsFormData.id) {
        //编辑模式
        // depts.filter(item=>item.pid===this.addDeptsFormData.pid && item.id !== this.addDeptsFormData.id)
        isRepeat = depts
          .filter(
            item =>
              item.pid === this.treeNode.pid && item.id !== this.treeNode.id
          )
          .some(item => item.name === value);
      } else {
        //新增模式
        // 去找同级部门下,有没有和value 相同的值
        //找到同级部门下所有的子部门
        isRepeat = depts
          .filter(item => item.pid === this.treeNode.id)
          .some(item => item.name === value);
      }
      // 如果isRepeat为true  表示找到了一样的名字
      isRepeat ? callback(new Error(`同级部门下已经存在${value}`)) : callback();
    };
    const checkCodeRepeat = async (rule, value, callback) => {
      const { depts } = await getDepartments();
      let isRepeat = false;
      if (this.addDeptsFormData.id) {
        isRepeat = depts
          .filter(item => item.id !== this.treeNode.id)
          .some(item => item.code === value && value);
      } else {
        // 这里加一个 value不为空 ,因为我们的部门数据库中,有可能没有code
        isRepeat = depts.some(item => item.code === value && value);
      }
      isRepeat
        ? callback(new Error(`组织架构中已经有部门使用${value}`))
        : callback();
    };
    return {
      addDeptsFormData: {
        name: "",
        //部门编码
        code: "",
        manager: "",
        //部门介绍
        introduce: ""
      },
      //校验规则
      addDeptsRules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门名称长度为1到50个字符",
            trigger: "blur"
          },
          { trigger: "blur", validator: checkNameRepeat }
        ],
        //部门编码
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门编码长度为1到50个字符",
            trigger: "blur"
          },
          {
            trigger: "blur",
            validator: checkCodeRepeat
          }
        ],
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" }
        ],
        //部门介绍
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          {
            min: 1,
            max: 300,
            message: "部门介绍长度为1到300个字符",
            trigger: "blur"
          }
        ]
      },
      //简单员工列表
      peoples: []
    };
  },
  computed: {
    //显示控制标题
    showTitle() {
      return this.addDeptsFormData.id ? "编辑部门" : "新增子部门";
    }
  },
  methods: {
    async getEmployeeSimple() {
      this.peoples = await getEmployeeSimple();
    },
    //添加 addDepts
    btnOk() {
      //手动校验表单
      this.$refs.addDeptsFormRef.validate(async isOk => {
        //校验通过
        if (isOk) {
          if (this.addDeptsFormData.id) {
            //编辑
            await updateDepartments(this.addDeptsFormData);
          } else {
            //将当前节点的id 设置为新的部门的pid
            await addDepartments({
              ...this.addDeptsFormData,
              pid: this.treeNode.id
            });
          }
          //告诉父组件,新增数据成功,重新拉取数据
          this.$emit("addDepts"); //触发一个自定义事件
          //关闭弹层,修改 showDialog 的值
          // this.$emit('changeDialog',false)
          //update:props 名称,值
          this.$emit("update:showDialog", false);
          //关闭 dialog 的时候,会去触发 el-dialog的close事件 不需要单独重制数据
        }
      });
    },
    //取消
    btnCancel() {
      // 重置数据  因为resetFields 只能重置 表单上的数据 非表单上的 比如 编辑中id 不能重置
      this.addDeptsFormData = {
        name: "",
        code: "",
        manager: "",
        introduce: ""
      };
      this.$emit("update:showDialog", false);
      //清除之前的校验数据
      this.$refs.addDeptsFormRef.resetFields();
    },
    //获取详情方法
    async getDepartmentDetail(id) {
      this.addDeptsFormData = await getDepartmentDetail(id);
    }
  }
};
</script>
